package com.vecharm.app.ui.web


import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Intent
import android.os.Bundle
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import com.ling.sdk.app.App
import com.ling.sdk.ui.BaseFragment
import com.tencent.sonic.sdk.SonicConfig
import com.tencent.sonic.sdk.SonicEngine
import com.tencent.sonic.sdk.SonicSession
import com.tencent.sonic.sdk.SonicSessionConfig
import com.vecharm.app.R
import com.vecharm.app.ui.smartlable.IAction
import kotlinx.android.synthetic.main.fragment_web.*

class WebFragment : BaseFragment(), IAction {


    override fun preload(urls: ArrayList<String>?) {
        urls?.forEach { preload(it) }
    }

    override fun onStartPlay() {

    }

    override fun onPausePlay() {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initSonic()
    }


    override fun getLayoutId() = R.layout.fragment_web


    override fun onInitView() {
        initWebView(webView)
        sonicLoadUrl(webView, getUrl())
    }


    private fun getUrl() = arguments?.getStringArrayList("list")?.getOrNull(0) ?: ""


    override fun onDestroyView() {
        super.onDestroyView()
        webView?.destroy()
        sonicSession?.destroy()
        sonicSession = null
    }


//===========================================vasSonic=========================================================//

    private fun initSonic() {
        checkInit()
        val sessionConfigBuilder = SonicSessionConfig.Builder().setSupportLocalServer(true)
        // create sonic session and run sonic flow
        if (sonicSession == null) {
            sonicSession = SonicEngine.getInstance().createSession(getUrl(), sessionConfigBuilder.build())
            if (null != sonicSession) {
                sonicSession?.bindClient(SonicSessionClientImpl())
            }
        }
    }

    private fun checkInit() {
        // init sonic engine
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(SonicRuntimeImpl(App.app), SonicConfig.Builder().build())
        }

    }

    private var sonicSession: SonicSession? = null


    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView(web: WebView?) {
        web ?: return

        SonicRuntimeImpl.cacheUserAgent(web.settings.userAgentString)

        web.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                sonicSession?.sessionClient?.pageFinish(url)
            }

            @TargetApi(21)
            override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
                return shouldInterceptRequest(view, request.url.toString())
            }

            override fun shouldInterceptRequest(view: WebView?, url: String?): WebResourceResponse? {
                return sonicSession?.sessionClient?.requestResource(url) as? WebResourceResponse
            }
        }

        val webSettings = web.settings
        webSettings.allowContentAccess = true
        webSettings.databaseEnabled = true
        webSettings.domStorageEnabled = true
        webSettings.setAppCacheEnabled(true)
        webSettings.savePassword = false
        webSettings.saveFormData = false
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptEnabled = true

        val clientImpl = sonicSession?.sessionClient as? SonicSessionClientImpl

        val intent = Intent().putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis())
        web.addJavascriptInterface(SonicJavaScriptInterface(clientImpl, intent), "sonic")

    }


    private fun sonicLoadUrl(web: WebView?, url: String) {
        web ?: return
        val clientImpl = sonicSession?.sessionClient as? SonicSessionClientImpl

        if (clientImpl != null) {

            clientImpl.bindWebView(web)
            clientImpl.clientReady()
        } else { // default mode
            web.loadUrl(url)
        }
    }

    private fun preload(url: String) {
        // init sonic engine
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(SonicRuntimeImpl(App.app), SonicConfig.Builder().build())
        }

        val sessionConfigBuilder = SonicSessionConfig.Builder().setSupportLocalServer(true)
        // preload session
        val preloadSuccess = SonicEngine.getInstance().preCreateSession(url, sessionConfigBuilder.build());

    }

}
